package cn.com.xy.sms.sdk.tagsearch;

import android.text.TextUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.util.StringUtils;
import cn.com.xy.sms.sdk.util.ThreadPoolManager;

/**
 * @author kwb1
 * @version 1.0
 * @created 17-02-2017 16:37:48
 * jira : HUAWEI-2296
 */
public class TagCacheManager {
    private final String TAG = "TagCacheManager";

    private static TagCacheManager sTagCacheManager = null;
    private Map<String, TagItem> mTagFirstScenesMap = new HashMap<String, TagItem>();
    private Map<String, TagItem> mTagSecondScenesMap;
    private List<String> msgSceneList = new ArrayList<String>();
    private boolean isUpdate = false;

    private TagCacheManager() {
    }

    public static TagCacheManager getInstance() {
        synchronized (TagCacheManager.class) {
            if (sTagCacheManager == null) {
                sTagCacheManager = new TagCacheManager();
            }
        }
        return sTagCacheManager;
    }

    public List<String> getFirstTags(List<String> sceneList) {

        // 获取本地所有一级标签
        if (mTagFirstScenesMap.size() == 0 || isUpdate) {
            mTagFirstScenesMap = TagDbManager.getInstance().getFirstTag();
            isUpdate = false;
        }
        // 若sceneList为空则返回所有标签
        if (sceneList == null || sceneList.size() == 0) {
            LogManager.e(TAG, "getFirstTags sceneList is empty");
            return new ArrayList<String>(mTagFirstScenesMap.keySet());
        }
        // 传进来的情景id 映射成五位情景id
        msgSceneList = sceneList;

        List<String> newSceneList = new ArrayList<String>();
        for (String id : sceneList) {
            if (TextUtils.isEmpty(id))
                continue;
            if (id.length() > 5)
                id = id.substring(0, 5);
            if (!newSceneList.contains(id)) {
                newSceneList.add(id);
            }
        }

        // 标签抽取
        List<String> tags = getFilterTag(mTagFirstScenesMap, newSceneList);

        // 标签更新检测
        new TagUpdateManager().updateTagData();
        return tags;
    }

    public List<String> getSecondTags(String tag1) {

        String tagId = null;
        if (mTagFirstScenesMap != null) {
            TagItem tagItem = mTagFirstScenesMap.get(tag1);
            if (tagItem != null) {
                tagId = tagItem.getTagId();
            }
        }
        if (StringUtils.isNull(tagId)) {
            tagId = TagDbManager.getInstance().getTagIdByTagName(tag1);
        }
        mTagSecondScenesMap = TagDbManager.getInstance().getSecondTag(tagId);
        List<String> tag = getFilterTag(mTagSecondScenesMap, msgSceneList);
        updateUseTime(tag1);
        return tag;
    }

    public List<String> getSceneIdList(String tag) {
        String sceneIds = null;
        if (mTagFirstScenesMap != null && mTagFirstScenesMap.containsKey(tag)) {
            TagItem tagItem = mTagFirstScenesMap.get(tag);
            if (tagItem != null)
                sceneIds = tagItem.getSceneIds();
        } else if (mTagSecondScenesMap != null && mTagSecondScenesMap.containsKey(tag)) {
            TagItem tagItem = mTagSecondScenesMap.get(tag);
            if (tagItem != null)
                sceneIds = tagItem.getSceneIds();
        }
        if (StringUtils.isNull(sceneIds)) {
            sceneIds = TagDbManager.getInstance().getSceneIdsByTagName(tag);
        }

        if (TextUtils.isEmpty(sceneIds))
            return null;
        String[] array = sceneIds.split(";");
        List<String> list = new ArrayList<String>();
        if (array != null) {
            for (String sceneId : array)
                if (!TextUtils.isEmpty(sceneId)) {
                    list.add(sceneId);
                }
        }
        return list;
    }

    public void clearCache() {
        if (mTagFirstScenesMap != null) {
            mTagFirstScenesMap.clear();
        }
        if (mTagSecondScenesMap != null)
            mTagSecondScenesMap.clear();
        if (msgSceneList != null)
            msgSceneList.clear();
    }

    public void setUpdateTrue() {
        isUpdate = true;
    }

    // --------------------------------- 私有方法 ---------------------------------

    private void updateUseTime(final String tag) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                TagDbManager.getInstance().updateUseCount(tag);
            }
        };
        ThreadPoolManager.NUMBER_QUERY.execute(runnable);
    }

    private List<String> getFilterTag(Map<String, TagItem> tagMap, List<String> sceneIdList) {
        List<String> tags = new ArrayList<String>();
        List<String> keys = new ArrayList<String>(tagMap.keySet());

        if (sceneIdList != null) {
            for (String id : sceneIdList) {
                for (String key : keys) {
                    TagItem tagItem = tagMap.get(key);
                    String sceneIds;
                    if (tagItem == null)
                        continue;
                    else {
                        sceneIds = tagItem.getSceneIds();
                    }
                    if (sceneIds == null)
                        continue;
                    else {
                        if (!TextUtils.isEmpty(id) && sceneIds.contains(id) && !tags.contains(key)) {
                            tags.add(key);
                            break;
                        }
                    }
                }
            }
        }

        return tags;
    }

    private Map<String, Integer> sortMapByValue(Map<String, Integer> oriMap) {
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        if (oriMap != null && !oriMap.isEmpty()) {
            List<Map.Entry<String, Integer>> entryList = new ArrayList<Map.Entry<String, Integer>>(oriMap.entrySet());
            Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
                public int compare(Map.Entry<String, Integer> entry1, Map.Entry<String, Integer> entry2) {
                    int value1, value2;
                    try {
                        value1 = entry1.getValue();
                        value2 = entry2.getValue();
                    } catch (NumberFormatException e) {
                        value1 = 0;
                        value2 = 0;
                    }
                    return value2 - value1;
                }
            });
            Iterator<Map.Entry<String, Integer>> iter = entryList.iterator();
            Map.Entry<String, Integer> tmpEntry;
            while (iter.hasNext()) {
                tmpEntry = iter.next();
                sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
            }
        }
        return sortedMap;
    }

    public static class TagItem {
        private String tagId;
        private String sceneIds;

        public TagItem(String tagId, String sceneIds) {
            this.tagId = tagId;
            this.sceneIds = sceneIds;
        }

        public String getTagId() {
            return tagId;
        }

        public String getSceneIds() {
            return sceneIds;
        }
    }
}